<template>
	<view class="content">
		<u-row>
			<u-col span="4" offset="4" textAlign="center">
				<u-icon name="tags-fill" label="温馨提示" color="#f29100" size="28"></u-icon>
			</u-col>
		</u-row>
		<view class="box-crad">
			<p>我只是一个仅供学习使用的模拟扫码支付App，处理逻辑较为简单，仅以实现扫码支付的操作为目的。</p>
			<p>大家使用的时候，可根据自己的业务逻辑需要进行代码重构。</p>
		</view>
		<u-row>
			<u-col span="4" offset="4" textAlign="center">
				<u-icon name="scan" color="#f29100" size="50" label="扫一扫" labelPos="bottom" @click="scanCode"></u-icon>
			</u-col>
		</u-row>
		<appreciation-code></appreciation-code>
	</view>
</template>

<script>
	import md5 from "js-md5"
	import dayjs from "dayjs"

	export default {
		data() {
			return {
			}
		},
		onLoad() {},
		onShow() {
		},
		methods: {
			verify_scan_result(res) {
				let date = dayjs(res.timeMillis).add(res.expireMillis, 'millisecond');
				let diffTime = dayjs(date).diff(dayjs(), 'second');
				
				if (diffTime <= 0) {
					uni.showToast({
						icon: 'error',
						position: 'top',
						title: '订单已失效',
						duration: 2000
					});
					return false;
				}
				return true;
			},
			dispose_scan_result(result) {
				uni.navigateTo({
					url: '/pages/payment/payment',
					success: function(res) {
						// 通过eventChannel向被打开页面传送数据
						res.eventChannel.emit('acceptDataFromOpenerPage', {
							order: result
						})
					}
				})
			},
			scanCode() {
				uni.getStorage({
					key: 'token',
					success: res => {
						uni.showLoading({
							title: '加载中...',
							mask: true
						});
						// 只允许通过相机扫码
						uni.scanCode({
							onlyFromCamera: true,
							scanType: ['qrCode'],
							success: res => {
								try{
									let result = JSON.parse(res.result);
									if(this.verify_scan_result(result)) this.dispose_scan_result(result);
								}catch(e){
									uni.showToast({
										icon: 'error',
										position: 'top',
										title: '错误二维码',
										duration: 2000
									});
								}
								uni.hideLoading();
							},
							fail: res => {
								uni.hideLoading();
							}
						});
					},
					fail: res => {
						uni.showToast({
							icon: 'error',
							title: '请登录小程序',
							duration: 1000,
							complete() {
								setTimeout(() => {
									uni.switchTab({
										url: '/pages/account/account'
									})
								}, 1000)
							}
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.content {
		width: 100%;
		height: 100%;

		.box-crad {
			width: 650rpx;
			margin: auto;
			box-shadow: 2px 2px 4px 1px grey;
			text-indent: 2em; //首行缩进两个字符
			padding: 20rpx;
			color: #65676d;
		}
	}
</style>
